"""
《邢不行-2022新版|Python数字货币量化投资课程》
无需编程基础，助教答疑服务，专属策略网站，一旦加入，永续更新。
课程详细介绍：https://quantclass.cn/crypto/class
邢不行微信: xbx9025
本程序作者: 邢不行
优化作者：中央勤暴菊

# 课程内容
查找CCXT私有函数
"""
import time

import ccxt
import pandas as pd


def get_all_api(exchange):
    """
    获取CCXT的所有私有函数
    :param exchange: 实例化后的交易所变量
    :return:
    """
    _api_path_list = []
    all_api_dict = exchange.describe()['api']
    for first_k, first_v in all_api_dict.items():
        if isinstance(first_v, dict):
            for second_k, second_v in first_v.items():
                if second_k in ['get', 'post', 'put', 'delete'] and isinstance(second_v, dict):
                    for third_k, third_v in second_v.items():
                        last_path = ''.join([i[0].upper() + i[1:] for i in third_k.split('/')])
                        last_path = ''.join([i[0].upper() + i[1:] for i in last_path.split('-')])
                        _api_path = first_k + second_k[0].upper() + second_k[1:] + last_path
                        _api_path_list.append(_api_path)
    return _api_path_list


def get_private_functions(_api_word, _api_path_list):
    """
    根据API信息，获取私有函数
    :param _api_word:API接口信息（例子：GET /api/v5/public/price-limit）
    :param _api_path_list:所有私有函数合集
    :return:
    """
    method = _api_word.split()[0]
    api_name = _api_word.split()[1]
    api_type = api_name.split('/')[1] if 'api' in api_name else ''

    last_api_path_list = api_name.split('/')
    last_api_path_list = sum(list(map(lambda x: x.split('-'), last_api_path_list)), [])

    last_api_path = ''
    last_res_list = []
    for _last_api_path in reversed(last_api_path_list):
        res_list = []
        last_api_path = _last_api_path[0].upper() + _last_api_path[1:] + last_api_path
        for api_path in _api_path_list:
            if api_path.endswith(last_api_path) and method.capitalize() in api_path:
                if (api_type == 'api') and ('api' not in api_path):
                    res_list.append(api_path)
                elif (api_type != 'api') and (api_path.startswith(api_type)):
                    res_list.append(api_path)
        # print(res_list)
        if len(res_list) == 1:
            return res_list
        if len(res_list) == 0:
            return last_res_list
        last_res_list = res_list

    return last_res_list


# 币安常用的api函数
def api_test():
    # =====交易所配置
    proxy = {'http': 'http://127.0.0.1:7890', 'https': 'http://127.0.0.1:7890'}
    exchange = ccxt.binance({
        # mpharaoh666888账户
        'apiKey': "IWutqYrDM6PNgMDyaJMzq1SvEeZONxJkVIKe59rmEdafZ327GMXUmQDMC9zxO8G9",
        'secret': "NmzBMlndNRyJfsXj8YjnXeuDYDqk1WYZUkDK38U3FOzYih8ZZnTmC5LzsX724Pq5",
        'timeout': 30000,
        'rateLimit': 10,
        'enableRateLimit': False,
        'options': {
            'adjustForTimeDifference': True,
            'recvWindow': 10000,
        },
        # 'proxies': proxy
    })

    params = {
        'symbol': 'BTCUSDT',
        'timestamp': int(time.time() * 1000)
    }

    # ===U本位合约接口===
    # 获取账户损益资金流水 (USER_DATA)
    # GET /fapi/v1/income (HMAC SHA256)
    res = exchange.fapiPrivateGetIncome(params=params)
    print(pd.DataFrame(res), '\n')

    # 用户手续费率 (USER_DATA)
    # GET /fapi/v1/commissionRate (HMAC SHA256)
    res = exchange.fapiPrivateGetCommissionRate(params=params)
    print(res, '\n')

    # 杠杆分层标准 (USER_DATA)
    # GET /fapi/v1/leverageBracket
    res = exchange.fapiPrivateGetLeverageBracket(params=params)
    for symbol in res:
        print(pd.DataFrame(symbol['brackets']))
    print('\n')

    # 获取未平仓合约数
    # GET /fapi/v1/openInterest
    res = exchange.fapiPublicGetOpenInterest(params=params)
    print(res, '\n')

    # ohlcv获取k线 默认1000根
    res = exchange.fetch_ohlcv(symbol='BTC/USDT', timeframe='5m')
    print(pd.DataFrame(res), '\n')

    # ===币本位合约接口===
    # 获取交易规则和交易对
    # GET /dapi/v1/exchangeInfo
    res = exchange.dapiPublicGetExchangeInfo()
    print(res)


if __name__ == '__main__':
    exchange = ccxt.binance()
    api_path_list = get_all_api(exchange)
    # print(api_path_list)
    while True:
        api_word = input('请输入API接口信息：')
        print(get_private_functions(api_word, api_path_list))
